from turtle import home
from flask import Flask, g, request
from extension import db, cache
from extension import login_manager, mail, jwt
from config import Config
from flask_cors import CORS
from views.user import user_bp
from views.course import course_bp
from views.file_manage import fm_bp
from views.teacher import teacher_bp
from views.homework import homework_bp
from views.groups import groups_bp
from views.exam import exam_bp
from views.notice import notice_bp
from views.ai_service import ai_bp
from views.discuss import discuss_bp
from model import *
from sqlalchemy import text

app = Flask(__name__)

app.config.from_object(Config)
db.init_app(app)
login_manager.init_app(app)
mail.init_app(app)
cache.init_app(app)
jwt.init_app(app)



# with app.app_context():
#     # 使用连接对象执行原始 SQL 语句
#     with db.engine.connect() as connection:
#         # 禁用外键检查
#         connection.execute(text('SET FOREIGN_KEY_CHECKS=0;'))
#
#         # 删除 Group 表，使用 checkfirst=True 避免表不存在时出错
#         Group.__table__.drop(db.engine, checkfirst=True)
#
#         # 启用外键检查
#         connection.execute(text('SET FOREIGN_KEY_CHECKS=1;'))
#
#     # 重新创建 Group 表
#     Group.__table__.create(db.engine)

# 在应用上下文中执行

# with app.app_context():
#     # 禁用外键检查
#     with db.engine.connect() as connection:
#         connection.execute(text('SET FOREIGN_KEY_CHECKS=0;'))
#
#     # 删除指定的表
#     db.metadata.drop_all(bind=db.engine, tables=[DiscussionPost.__table__, DiscussionReply.__table__])
#
#     # 启用外键检查
#     with db.engine.connect() as connection:
#         connection.execute(text('SET FOREIGN_KEY_CHECKS=1;'))
#
#     # 使用 SQLAlchemy 的 create_all 方法来创建所有表
#     DiscussionPost.__table__.create(bind=db.engine)
#     DiscussionReply.__table__.create(bind=db.engine)


CORS(app, supports_credentials=True)

app.register_blueprint(user_bp, url_prefix='/user')
app.register_blueprint(course_bp, url_prefix='/course')
app.register_blueprint(fm_bp, url_prefix='/file_manage')
app.register_blueprint(teacher_bp, url_prefix='/teacher')
app.register_blueprint(homework_bp, url_prefix='/homework')
app.register_blueprint(groups_bp, url_prefix='/groups')
app.register_blueprint(exam_bp, url_prefix='/exam')
app.register_blueprint(notice_bp, url_prefix='/notice')
app.register_blueprint(ai_bp, url_prefix='/ai_service')
app.register_blueprint(discuss_bp, url_prefix='/discuss')


@app.route('/')
def hello_world():  # put application's code here
    return 'Hello World!'


if __name__ == '__main__':

    #app.run(host='192.168.10.130', port=5000,debug=True) #113-5g
    # app.run(host='172.19.36.98', port=5000)
    #app.run(host='10.60.23.182', port=5000) #web
    #app.run(host='192.168.47.127',port=5000)
    #app.run(host='192.168.10.58', port=5000) #opporeno8pro+
    app.run(port=5000)
